package com.lams.service.corpus.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.sql.SQLException;

import com.lams.jdbc.QueryUtils;
import com.lams.service.BaseFacade;
import com.lams.service.corpus.ISearchFacade;
import com.lams.util.DateHelper;
import com.lams.util.IdFactory;
import com.lams.util.ResultEntity;
import com.lams.util.SqlBean;

public class SearchFacade extends BaseFacade<SearchFacade> implements ISearchFacade {
	private static Map<String, List<Map<String, String>>> dataMap = new HashMap<String, List<Map<String, String>>>();
	private static long SAVETIME = 1000 * 60 * 60l; // 保存时间 1小时
	private static long BEGINTIME = 0l; // 记录存入时间
	private String searchSql;
	/**
	 * 查询作品SQL编码
	 */
	private String queryArticle;
	/**
	 * 添加作品SQL编码
	 */
	private String addArticle;
	/**
	 * 更新SQL
	 */
	private String updateArticle;
	private String deleteArticle;

	private List<Map<String, String>> searchByKey(String key,int leftNum,int rightNum) {
		if (System.currentTimeMillis() - SearchFacade.BEGINTIME > SearchFacade.SAVETIME)
			SearchFacade.dataMap.clear();
		List<Map<String, String>> data = SearchFacade.dataMap.get(key);
		if (data == null) {
			Map params = new HashMap();
			params.put("query", key);
			String sql = QueryUtils.getSqlBySqlCode(searchSql, params);
			List<Map> list = QueryUtils.executeQuery(sql);
			List<Map<String, String>> result = new ArrayList<Map<String, String>>();
			for (Iterator<Map> iterator = list.iterator(); iterator.hasNext();) {
				Map<String, String> item = iterator.next();
				String content = item.get("CONTENT");
				String[] contents = content.split(key);
				String start = "", end = "";
				String s = "";
				for (int i = 0; i < contents.length; i++) {
					String object = contents[i].trim();
					if (i == 0) {
						start = object.substring(
								object.length() > leftNum ? (object.length() - leftNum)
										: 0, object.length());
					} else {
						end = object.substring(0, object.length() > rightNum ? rightNum
								: object.length());
						s = start + key + end;
						Map map = new HashMap();
						map.putAll(item);
						map.put("CONTENT", s);
						result.add(map);
						start = object.substring(
								object.length() > 30 ? (object.length() - 30)
										: 0, object.length());

					}
				}
			}
			SearchFacade.BEGINTIME = System.currentTimeMillis();
			SearchFacade.dataMap.put(key, result);
			data = result;
		}
		return data;
	}

	private List<Map<String, String>> searchByKey(String[] key,int leftNum,int rightNum) {
		List<Map<String, String>> list = this.searchByKey(key[0],leftNum,rightNum);
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		if (key.length >= 2) {
			for (Iterator<Map<String, String>> iterator = list.iterator(); iterator
					.hasNext();) {
				Map<String, String> object = iterator.next();
				String content = object.get("CONTENT");
				// 判断是否出现第二关键字并且出现在第一关键字之后
				if (content.indexOf(key[1]) != -1
						&& content.indexOf(key[1]) > content.indexOf(key[0]))
					result.add(object);
			}
		} else {
			result = list;
		}
		return result;
	}
	
	/* (non-Javadoc)
	 * @see com.lams.service.corpus.impl.ISearchFacade#search(int, int, java.lang.String[])
	 */
	@Override
	public ResultEntity search(int start,int limit,Map params){
		String[] keys = (String[]) params.get("KEY");
		int leftNum = (Integer) params.get("LEFTNUM");
		int rightNum = (Integer) params.get("RIGHTNUM");
//		String red = "<font color='red'>"+keys[0].trim()+"</font>";
//		String red1 = "";
//		if(keys.length>=2)
//			red1 = "<font color='red'>"+keys[1].trim()+"</font>";
		List<Map<String,String>> data = this.searchByKey(keys,leftNum,rightNum);
		List <Map<String,String>> list = new ArrayList<Map<String,String>>();
		for(int i=start;i<start+limit;i++){
			if(i==data.size()) break;
			Map<String,String> item = data.get(i);
			String content = item.get("CONTENT");
			content = content.replaceAll(keys[0], "<font color='red'><b>"+keys[0].trim()+"</b></font>");
			if(keys.length >= 2)
				content = content.replaceAll(keys[1], "<font color='red'><b>"+keys[1].trim()+"</b></font>");
			item.put("CONTENT", content);
			list.add(data.get(i));
			//System.out.println(content);
		}
		ResultEntity result = new ResultEntity(list, data.size());
		return result;
	}

	public void setSearchSql(String searchSql) {
		this.searchSql = searchSql;
	}
	
	public ResultEntity queryArticle(Map params, int start, int limit) {
		SqlBean sqlbean = QueryUtils.getSqlBySqlCode(queryArticle);
		int totalCount = QueryUtils.getTotalCount(sqlbean.getContent());
		List data = QueryUtils.executeQuery(start, limit, sqlbean.getContent());
		ResultEntity result = new ResultEntity();
		result.setData(data);
		result.setTotalCount(totalCount);
		result.setSuccess(true);
		return result;
	}
	
	public ResultEntity addOrUpdateArticle(Map params, String type) {
		String ssql;
		ResultEntity result = new ResultEntity();
		if("add".equals(type) || "update".equals(type)){
			if("add".equals(type)){
				params.put("ARTICLE_ID", IdFactory.getNextNav("l_article", "article_id"));
			}       
			ssql = QueryUtils.getSqlBySqlCode("add".equals(type)?this.addArticle:this.updateArticle, params);
			int flag;
			try {
				flag = super.getDao().executeUpdate(ssql);
				result.setSuccess(true);
				result.setMessage("执行操作成功");
			} catch (SQLException e) {
				e.printStackTrace();
				result.setSuccess(true);
				result.setMessage("执行操作失败");
			}
		} else{
			result.setSuccess(false);
			result.setMessage("更新类型错误");
		}
		return result;
	}
	@Override
	public ResultEntity deleteArticle(Map params) {
		
		return null;
	}
	public String getQueryArticle() {
		return queryArticle;
	}

	public void setQueryArticle(String queryArticle) {
		this.queryArticle = queryArticle;
	}

	public String getAddArticle() {
		return addArticle;
	}

	public void setAddArticle(String addArticle) {
		this.addArticle = addArticle;
	}

	public String getUpdateArticle() {
		return updateArticle;
	}

	public void setUpdateArticle(String updateArticle) {
		this.updateArticle = updateArticle;
	}

	public void setDeleteArticle(String deleteArticle) {
		this.deleteArticle = deleteArticle;
	}
	
}
